package org.mayuanxiaonong.timserver.handler.deliver;

import java.util.concurrent.BlockingQueue;

import org.mayuanxiaonong.timserver.channel.ChannelManager;
import org.mayuanxiaonong.timserver.packet.LoginPacket;
import org.mayuanxiaonong.timserver.packet.MessagePacket;
import org.mayuanxiaonong.timserver.packet.Packet;
import org.mayuanxiaonong.timserver.config.SystemConfig;
import org.mayuanxiaonong.timserver.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 消息分发器
 * 
 * @author 9527
 *
 */
public class PacketHandler implements Runnable {

	private static final Logger log = LoggerFactory
			.getLogger(PacketHandler.class);
	private BlockingQueue<Packet> queue;
	private UserService userService = SystemConfig.getInstance().getBean(UserService.class);

	public PacketHandler(BlockingQueue<Packet> queue) {
		this.queue = queue;
	}

	@Override
	public void run() {
		while (queue.size() > 0) {
			Packet packet = queue.poll();
			if (packet != null) {
				handle(packet);
			}
		}
	}

	private void handle(final Packet packet) {
		switch (packet.getType()) {
		case Packet.Type.LOGIN:
			handleLogin((LoginPacket) packet);
			break;
		case Packet.Type.MESSAGE:
			handleMessage((MessagePacket) packet);
			break;
		default:
			break;
		}
	}

	public void handleLogin(LoginPacket packet) {
		boolean ok = userService.login(packet.getUserid(), packet.getToken());
		
	}

	public void handleMessage(MessagePacket packet) {
		ChannelManager.getChannel(packet.getTo()).writeAndFlush(packet);
	}

}
